package com.gosuncn.config.pdf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ARMHtmlToPdf extends AbstractHtmlToPdf {

    private static Logger logger = LoggerFactory.getLogger(ARMHtmlToPdf.class);

    /** 字体文件名 */
    private static final String FONT_FILE_NAME = "simsun.ttc";

    /** linux字体文件目录 */
    private static final String FONT_FOLDER = "/usr/share/fonts/";

    @Override
    public SystemTool getSystemTool() {
        return SystemTool.ARM;
    }

    @Override
    public void initCommand() {
        try {
            Process process = Runtime.getRuntime().exec("chmod +x " + toolPath);
            ProcessStreamHandler.handle(process);
        } catch (IOException e) {
            logger.error("执行授权工具出现异常：{}", e.getMessage());
        }
        initFonts();
    }

    private void initFonts() {
        File fontFile = new File(FONT_FOLDER, FONT_FILE_NAME);
        try (InputStream is = ResourceUtils.getURL("classpath:wkhtmltopdf/" + FONT_FILE_NAME).openStream();
                FileOutputStream fos = new FileOutputStream(fontFile)) {
            byte[] buffer = new byte[1024];
            int lenght = 0;
            while ((lenght = is.read(buffer)) != -1) {
                fos.write(buffer, 0, lenght);
            }
        } catch (IOException e) {
            logger.error("初始化Linux字体出现异常", e);
        }
    }

}
